package com.xry.test1.Interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.xry.test1.Util.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;



public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true; // 预检请求，直接放行
        }
        String token = request.getHeader("Authorization");

        // 兼容 Bearer 开头的 token
        if (token == null || token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            returnJson(response, "未携带 token");
            return false;
        }

        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        try {
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            // 将用户名等信息存入 request，供后续 Controller 使用
            String username = decodedJWT.getClaim("username").asString();
            Long userId = decodedJWT.getClaim("userId").asLong(); // 如果你生成 token 时加了 userId
            request.setAttribute("username", username);
            request.setAttribute("userId", userId);
            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            returnJson(response, "token 无效或已过期");
            return false;
        }
    }

    private void returnJson(HttpServletResponse response, String msg) {
        response.setContentType("application/json;charset=UTF-8");
        try {
            response.getWriter().write("{\"code\":401,\"message\":\"" + msg + "\"}");
        } catch (Exception ignored) {
        }
    }
}


